package com.wjj.sixinone.common.util;

import com.wjj.sixinone.common.enums.ExceptionEnum;
import com.wjj.sixinone.common.exception.GlobalException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class CurrentIpUtils {

    /**
     * 默认IP地址
     */
    public final static String ERROR_IP = "127.0.0.1";

    public static String getUserIP() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes==null){
            throw new GlobalException(ExceptionEnum.ERROR_REQUEST_CONTEXT);
        }

        HttpServletRequest request = requestAttributes.getRequest();
        String ip = extractIpFromHeader(request, "X-Real-IP");

        if (isInvalidIp(ip)) {
            ip = extractIpFromHeader(request, "x-forwarded-for");
        }

        if (isInvalidIp(ip)) {
            ip = request.getRemoteAddr();
            if ("0:0:0:0:0:0:0:1".equals(ip)) {
                ip = ERROR_IP;
            }
        }

        if (isInvalidIp(ip)) {
            ip = ERROR_IP;
        } else {
            ip = extractFirstIp(ip);
        }

        return ip;
    }

    private static String extractIpFromHeader(HttpServletRequest request, String headerName) {
        String ip = request.getHeader(headerName);
        return (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) ? null : ip;
    }

    private static boolean isInvalidIp(String ip) {
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }

    private static String extractFirstIp(String ip) {
        int index = ip.indexOf(',');
        if (index >= 0) {
            ip = ip.substring(0, index);
        }
        return ip;
    }
}
